<?php
/**
 * Author: lf
 * Blog: https://blog.feehi.com
 * Email: job@feehi.com
 * Created at: 2016-04-07 11:37
 */

namespace backend\models;

use yii;
use yii\web\UploadedFile;
use yii\behaviors\TimestampBehavior;
use yii\helpers\FileHelper;

class FriendLink extends \common\models\FriendLink
{

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    public function beforeSave($insert)
    {
        $this->image = UploadedFile::getInstance($this, 'image');
        if ($this->image !== null) {
            $uploadPath = yii::getAlias('@friendlylink/');
            if (! FileHelper::createDirectory($uploadPath)) {
                $this->addError('thumb', "Create directory failed " . $uploadPath);
                return false;
            }
            $fullName = $uploadPath . uniqid() . '_' . $this->image->baseName . '.' . $this->image->extension;
            if (! $this->image->saveAs($fullName)) {
                $this->addError('thumb', yii::t('app', 'Upload {attribute} error', ['attribute' => yii::t('app', 'Thumb')]) . ': ' . $fullName);
                return false;
            }
            $this->image = str_replace(yii::getAlias('@frontend/web'), '', $fullName);
        }
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }
}